package kidsProjectClient;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map.Entry;

public class ClientNode {
	private String serverAddress;
	private Integer serverPort, localPort;
	private DatagramSocket clientSocket;
	private List<Entry<Integer, Integer>> opsezi;
	private volatile boolean finished;
	private int pocetak, kraj;
	private byte[] receiveData, sendData;
	private DatagramPacket receivePacket;

	private List<Integer> prosti;
	private volatile double percentageComplete;

	public ClientNode(InetAddress serverAddress, int serverPort,
			DatagramSocket clientSocket2) {
		System.out.println("NEW CLIENT NODE!!!");
		this.serverAddress = serverAddress.getHostName();
		this.serverPort = serverPort;
		this.localPort = clientSocket2.getLocalPort();
		clientSocket2.close();
		receiveData = new byte[512]; // paketi send i recieve su 512 bajta
		sendData = new byte[512];
		receivePacket = new DatagramPacket(receiveData, receiveData.length);
		try {
			clientSocket = new DatagramSocket(this.localPort,
					InetAddress.getLocalHost());
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void start() {
		Thread communication = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						receiveData = new byte[512];
						clientSocket.receive(receivePacket);
					} catch (IOException e) {
						e.printStackTrace();
					}
					String request = new String(receivePacket.getData()).trim();
					if (request.equals("[REGISTER_REQUEST]|[NEW_CLIENT]")) {
						String response = "[REGISTER_RESPONSE_CLIENT]|"
								+ serverAddress + ":" + serverPort;
						System.out.println(serverAddress);
						sendData = response.getBytes();
						DatagramPacket sendPacket = new DatagramPacket(
								sendData, sendData.length, receivePacket
										.getAddress(), receivePacket.getPort());
						try {
							clientSocket.send(sendPacket);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
		communication.start();

		while (true) {
			// trazi proste
		}
	}

	/*
	 * public void setOpseg(String opseg) { opsezi = new
	 * ArrayList<Entry<Integer, Integer>>(); String[] split1 = opseg.split(".");
	 * for (String string : split1) { String[] split2 = string.split(",");
	 * Entry<Integer, Integer> range = new AbstractMap.SimpleEntry<Integer,
	 * Integer>( Integer.parseInt(split2[0]), Integer.parseInt(split2[1]));
	 * opsezi.add(range); } }
	 */

	/*
	 * public void start(Socket node, BufferedReader inNode, PrintWriter
	 * outNode, int inPort) throws IOException { this.localPort = inPort; String
	 * line = inNode.readLine(); String line2 = inNode.readLine(); node.close();
	 * 
	 * InetAddress address = InetAddress.getByName(line); Integer port =
	 * Integer.parseInt(line2);
	 * 
	 * serverAddress = address; serverPort = port;
	 * 
	 * serverSocket = new Socket(serverAddress, serverPort); inServer = new
	 * BufferedReader(new InputStreamReader( serverSocket.getInputStream()));
	 * outServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
	 * serverSocket.getOutputStream())), true);
	 * 
	 * outServer.println("#NEW_CLIENT$");
	 * 
	 * String mojOpseg; mojOpseg = inServer.readLine(); setOpseg(mojOpseg);
	 * prosti = new ArrayList<Integer>(); percentageComplete = 0.0; finished =
	 * false;
	 * 
	 * Thread findPrimeNumbers = new Thread(new Runnable() {
	 * 
	 * public void run() { for (int i = pocetak; i < kraj; i++) {
	 * percentageComplete = ((double) (kraj - pocetak) / (double) (i - pocetak))
	 * * 100;//SREDITI OVO if (prost(i)) { prosti.add(i); } } finished = true;
	 * outServer.println("#FINISHED$"); for (Integer broj : prosti) {
	 * outServer.println(broj); } outServer.println("#OVER_AND_OUT$"); try {
	 * while (!inServer.ready() && !inServer.readLine().equals("#RESULTS$")) { }
	 * String results = inServer.readLine(); System.out.println("RESULTS: " +
	 * results); } catch (IOException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } }
	 * 
	 * private boolean prost(int i) { for (int j = 2; j < i; j++) { if (i % j ==
	 * 0) return false; } return true; } }); findPrimeNumbers.start();
	 * 
	 * Thread waitForConnections = new Thread(new Runnable() { public void run()
	 * { ServerSocket ss; try { ss = new ServerSocket(localPort); while (true) {
	 * if (finished) break; Socket buddy = ss.accept();
	 * 
	 * BufferedReader inBuddy; PrintWriter outBuddy;
	 * 
	 * inBuddy = new BufferedReader(new InputStreamReader(
	 * buddy.getInputStream())); outBuddy = new PrintWriter( new
	 * BufferedWriter(new OutputStreamWriter( buddy.getOutputStream())), true);
	 * 
	 * String query = inBuddy.readLine(); if (query.equals("#NEW_NODE$")) {
	 * outBuddy.println("#NOT_SERVER$"); outBuddy.println(serverAddress);
	 * outBuddy.println(serverPort); } buddy.close(); } } catch (IOException e)
	 * { // TODO Auto-generated catch block e.printStackTrace(); }
	 * 
	 * } }); waitForConnections.start();
	 * 
	 * Thread serverCommunication = new Thread(new Runnable() {
	 * 
	 * public void run() { while (true) { try { if (finished) break;
	 * outServer.println(percentageComplete); int attempts = 0; while
	 * (!inServer.ready() && attempts < 500) { // CEKAJ // NA // ODGOVOR
	 * attempts++; Thread.sleep(10); } if (inServer.ready()) { // SERVER POSLAO
	 * ODGOVOR String answer = inServer.readLine();
	 * System.out.println("PROCENA VREMENA I SVE OSTALO: " + answer);// TU CE
	 * SERVER SLATI STATUS POSLA } else { // PUKO SERVER }
	 * 
	 * Thread.sleep(5000); } catch (InterruptedException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } catch (IOException e) {
	 * // TODO Auto-generated catch block e.printStackTrace(); } } } });
	 * serverCommunication.start();
	 * 
	 * }
	 */

}
